//
//  SpecialSaleViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/27.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "SpecialSaleViewController.h"
#import "define.h"
#import "AsyncConnection.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "SpeacailSaleTableViewCell.h"
#import "SpecailDetailViewController.h"

@interface SpecialSaleViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, copy) NSString *flag;
@property (nonatomic, assign) CGFloat offHeigt;
@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, retain) NSDictionary *dic;
@property (nonatomic, retain) SpeacailSaleTableViewCell *cell;
@property (nonatomic, assign) NSInteger date;


@end

@implementation SpecialSaleViewController


- (void)dealloc
{
    [_dic release];
    [_cell release];
    
    [_table release];
    [_array release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.offHeigt = [[UIScreen mainScreen]bounds].size.height / 667;
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
        self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    }
    return self;
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addHeader
{
//    __block SpecialSaleViewController *actionVC = self;
    
    [self.table addHeaderWithCallback:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"刷新");
            //            [actionVC.collection reloadData];
            [self.table headerEndRefreshing];
        });
    }];
    [self.table headerBeginRefreshing];
}

- (void)addFooter
{
    
    __block SpecialSaleViewController *actionVC = self;
    
    [self.table addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            
            NSDictionary *ddd = @{@"visit":@"",
                                  @"flag":self.flag};
            [AsyncConnection asyncConnection:THREE_SPECAIL parmaters:ddd block:^(NSData *data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray *arr = [NSMutableArray array];
                arr = [[dic objectForKey:@"data"]objectForKey:@"items"];
                [self.array addObjectsFromArray:arr];
                
                
                [actionVC.table reloadData];
                
            }path:@"main_specail_sale"];
            
            [self.table footerEndRefreshing];
        });
    }];
    
    
    
}


- (void)baginConnection
{
    NSDictionary *dic = @{@"visit":@"",
                          @"flag":@""};
    
    [AsyncConnection asyncConnection:THREE_SPECAIL parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.dic = [dic objectForKey:@"data"];
        self.array = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self createTableView];
        self.flag = [[dic objectForKey:@"data"]objectForKey:@"flag"];
    }path:@"main_specail_sale"];
}

- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 69, self.view.frame.size.width, self.view.frame.size.height - 69) style:UITableViewStylePlain];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0 alpha:0.2];
    [self.table release];
    [self addFooter];
    [self addHeader];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (_cell == nil) {
        _cell = [[SpeacailSaleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
        _cell.dic = [self.array objectAtIndex:indexPath.row];
    }
    NSDictionary *dic = [[self.array objectAtIndex:indexPath.row]objectForKey:@"component"];
    [_cell.image sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    _cell.title.text = [dic objectForKey:@"title"];
    
    if ([[dic objectForKey:@"tuanState"]isEqualToString:@"正在抢购"]) {
        self.date = [[[[self.array objectAtIndex:indexPath.row]objectForKey:@"component"]objectForKey:@"expires"] integerValue];
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        NSString *day = [NSString stringWithFormat:@"%ld", _date / 3600 / 24];
        NSString *hour = [NSString stringWithFormat:@"%ld", _date / 3600 / 60];
        NSString *second = [NSString stringWithFormat:@"%ld", _date / 3600];
        [_cell.date setTitle:[[[[[day stringByAppendingString:@"天"]stringByAppendingString:hour]stringByAppendingString:@"时"]stringByAppendingString:second]stringByAppendingString:@"秒"] forState:UIControlStateNormal];
        _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else
    {
        [_cell.date setTitle:@"已结束" forState:UIControlStateNormal];
        _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    
    
    
    [_cell.people setTitle:[dic objectForKey:@"peopleCount"] forState:UIControlStateNormal];
    
    _cell.state.text = [dic objectForKey:@"tuanState"];
    if ([[dic objectForKey:@"tuanState"]isEqualToString:@"正在抢购"]) {
        _cell.state.backgroundColor = [UIColor colorWithRed:255/255 green:0 blue:255/255 alpha:0.5];
    }else
    {
        _cell.state.backgroundColor = [UIColor lightGrayColor];
        _cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
    
    return _cell;
}


- (void)timerFireMethod:(NSInteger)index
{
    self.date --;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200* _offHeigt;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [[self.array objectAtIndex:indexPath.row]objectForKey:@"component"];

    if ([[dic objectForKey:@"tuanState"] isEqualToString:@"正在抢购"]) {
        SpecailDetailViewController *detail = [[SpecailDetailViewController alloc]init];
        detail.dic = [[self.array objectAtIndex:indexPath.row]objectForKey:@"component"];
        detail.discount = [[[self.array objectAtIndex:indexPath.row]objectForKey:@"component"]objectForKey:@"title"];
        [self.navigationController pushViewController:detail animated:YES];
        [detail release];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self baginConnection];
    self.automaticallyAdjustsScrollViewInsets = NO;
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
